package com.cwits.wifi.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.ui.view.WaitDialog;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.IConstant;
import com.jieli.lib.stream.beans.StateInfo;
import com.jieli.lib.stream.tools.CommandHub;
import com.jieli.lib.stream.util.ICommon;

import java.io.File;


/**
 * Created by ZhangHua on 16-03-01.
 */
public class BaseFragment extends Fragment implements ICommon ,IAction,IConstant{
    private Toast mToastShort;
    private Toast mToastLong;
    private WaitDialog mProgressDialog;
    /** Fragment当前状态是否可见 */
    protected boolean isVisible;
    public MainApplication mApplication;

    //对于设备wifi状态监听
    public static int DEVICE_WIFI_ENABLED = 1;
    public static int DEVICE_WIFI_DISABLED = 2;
    public static int DEVICE_WIFI_CONNECTING = 3;
    public static int DEVICE_WIFI_CONNECTED = 4;
    private boolean mIsAutoDisabled_Device_WIFI = false;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
       // @Override
       // protected Object clone() throws CloneNotSupportedException {
       //     return super.clone();
        //}

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTION_DEVICE_WIFI_DISABLED:
                    mApplication.setErrorFlag(true);
                    mApplication.setIsOffLineMode(true);
                    mApplication.setRealCamera(false);
                    onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                    break;
                case ACTION_SDCARD_STATE:
                    StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_SDCARD_STATE);
                    break;
                case ACTION_DEVICE_CONNECTION_ERROR:

                    int errorType = intent.getIntExtra(KEY_DEVICE_CONNECTION_ERROR, -1);

                    Dbug.i("-----", "==errorType==" + errorType);
                    switch (errorType) {
                        case CommandHub.ERROR_CONNECTION_EXCEPTION:
                            mApplication.setErrorFlag(true);
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                            break;
                        case CommandHub.ERROR_CONNECTION_TIMEOUT:
                            mApplication.setErrorFlag(true);
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                            break;
                    }
                    onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                    break;
                case ACTION_REJECT_CONNECTION:
                    mApplication.setIsOffLineMode(true);
                    mApplication.setRealCamera(false);
                    onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                    break;
                case ACTION_REAR_CAMERA_PLUG_STATE:
                    StateInfo plugStateInfo = (StateInfo) intent.getSerializableExtra(KEY_REAR_CAMERA_PLUG_STATE);
                    String plugState = ARGS_NULL;
                    if(plugStateInfo != null) {
                        if (plugStateInfo.getParam().length >= 1) {
                            plugState = plugStateInfo.getParam()[0];
                            switch (plugState){
                                case ARGS_REAR_CAMERA_PLUG:
                                    Dbug.i("is_online_realcamera","后拉摄像头存在，code:" + plugState);
                                    mApplication.setRealCamera(true);
                                    onRealCameraState(true);
                                    break;
                                case ARGS_REAR_CAMERA_UNPLUG:
                                    Dbug.i("is_online_realcamera","后拉摄像头不存在,code:" + plugState);
                                    mApplication.setRealCamera(false);
                                    onRealCameraState(false);
                                    break;
                                default:
                                    Dbug.i("is_online_realcamera","后拉摄像头无法判断，code:" + plugState);
                                    mApplication.setRealCamera(false);
                                    onRealCameraState(false);
                                    break;
                            }
                        }
                    }
                    break;
                case ConnectivityManager.CONNECTIVITY_ACTION:
                    ConnectivityManager mConnectivityManager = (ConnectivityManager)mApplication.getSystemService(Context.CONNECTIVITY_SERVICE);
                    WifiManager wifiManager1 = (WifiManager)mApplication.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo11 = wifiManager1.getConnectionInfo();
                    String prefixSSID1 = "";
                    if(wifiInfo11 != null)
                        prefixSSID1 = wifiInfo11.getSSID().replace("\"", "");
                    NetworkInfo wifiInfo1 = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    if(wifiInfo1 != null&&wifiInfo11 != null &&(prefixSSID1.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID1.startsWith(WIFI_PREFIX_CARDVR)||prefixSSID1.contains(WIFI_PREFIX_168))&&TextUtils.isEmpty(wifiInfo11.getSSID()) == false)
                    {
                        //do nothing
                    }else
                    {
                        onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                        mApplication.setIsOffLineMode(true);
                        mApplication.setRealCamera(false);
                    }
                    break;
            }
        }
    };



    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    public void onWiFiState(boolean isAutoDisable, int state) {

    }

    public void onRealCameraState(boolean is_online) {

    }
    /**
     * 可见
     */
    protected void onVisible() {
    }


    /**
     * 不可见
     */
    protected void onInvisible() {


    }

    protected static String changeData(String data){

        return data.substring(0,4)+"-"+data.substring(4,6)+"-"+data.substring(6, data.length());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getActivity() == null){
            return;
        }
        mApplication = (MainApplication) getActivity().getApplication();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mApplication == null){
            mApplication = (MainApplication) getActivity().getApplication();
        }
        IntentFilter intentFilter = new IntentFilter(IAction.ACTION_DEVICE_WIFI_DISABLED);
        intentFilter.addAction(IAction.ACTION_SDCARD_STATE);
        intentFilter.addAction(ACTION_DEVICE_CONNECTION_ERROR);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(ACTION_REAR_CAMERA_PLUG_STATE);
//        intentFilter.addAction(IAction.ACTION_SDK_VERSION_NO_MATCH);
//        intentFilter.addAction(IAction.ACTION_APK_VERSION_NO_MATCH);
        this.getActivity().registerReceiver(mReceiver, intentFilter);
    }

    @Override
    public void onStop() {
        super.onStop();
        if(mReceiver != null)
        {
            this.getActivity().unregisterReceiver(mReceiver);
        }
    }

    public void showToastShort(String msg) {
        if(getActivity() == null){
            return;
        }
        if (mToastShort != null) {
            mToastShort.setText(msg);
        } else {
            mToastShort = Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT);
        }
        mToastShort.show();
    }
    public void showToast(String info) {
        if (mToastShort != null) {
            mToastShort.setText(info);
        } else {
            mToastShort = Toast.makeText(getActivity(), info, Toast.LENGTH_SHORT);
        }
        mToastShort.show();
    }

    public void showToast(int info) {
        showToast(getResources().getString(info));
    }

    public void showToastShort(int msg) {
        showToastShort(getResources().getString(msg));
    }

    public void showToastLong(String msg) {
        if(getActivity() == null){
            return;
        }
        if (mToastLong != null) {
            mToastLong.setText(msg);
        } else {
            mToastLong = Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG);
        }
        mToastLong.show();
    }

    public void showToastLong(int msg) {
        showToastLong(getResources().getString(msg));
    }

    public void changeFragment(int containerId, Fragment fragment) {

        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        fragmentTransaction.replace(containerId, fragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    protected void connectSuccess(){
        Toast toast = null;
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_connect_sucess,
                null);
        toast = new Toast(getActivity());
        toast.setGravity(Gravity.TOP, 0, 250);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

    protected void connectError(){
        Toast toast = null;
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_connect_cancle,
                null);
        toast = new Toast(getActivity());
        toast.setGravity(Gravity.TOP, 0, 250);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public void deleteFile(String path) {
        if (null == path) {
            return;
        }
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }

        dirFile.delete();
    }



}
